package com.flyoil.petromp.ui.activity.activity_repertory;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cnpc.fyutils.ToastUtils;
import com.cnpc.fyviewlibrary.view.ListScrollview;
import com.flyoil.petromp.Constant.ConstantNetworkCode;
import com.flyoil.petromp.R;
import com.flyoil.petromp.adapter.adapter_order.ItemOrderMessageSignatureAdapter;
import com.flyoil.petromp.apiservice.HttpModel;
import com.flyoil.petromp.apiservice.OnObserverRetrofitResetCallBack;
import com.flyoil.petromp.base.BaseActivity;
import com.flyoil.petromp.base.BaseEntity;
import com.flyoil.petromp.entity.entity_order.MapListEntity;
import com.flyoil.petromp.entity.entity_order.OrderSignatureEntity;
import com.flyoil.petromp.entity.entity_service.SupplierServiceMessageEntity;
import com.flyoil.petromp.utils.Dialog.DialogApproveUtil;
import com.flyoil.petromp.utils.Dialog.Dialog_util;
import com.flyoil.petromp.utils.OrderUtl.OrderMessageUtil;
import com.flyoil.petromp.utils.OrderUtl.OrderStatusUtil;
import com.flyoil.petromp.view.SignatureTopView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供应商服务详情信息界面
 */
public class ServiceMessageActivity extends BaseActivity {
    private LinearLayout line_text, line_supplier, line_img;
    private OrderMessageUtil orderMessageUtil;
    private int scrollviewYHeight = 0;//滑动的距离
    private View line_signature;//签字意见的分割线
    private TextView tv_signature, tv_signature_botton;//签字按钮、底部的签字按钮
    private ScrollView scrollView;//滑动控件
    private SignatureTopView signatureTopView;//自定义签字意见输入框
    private ListScrollview list_signature;//签字意见的布局
    private ItemOrderMessageSignatureAdapter adapter_signature;
    private RelativeLayout rela_layout;//滑动控件的父控件
    private int sigantureId=0;//单据的签字意见id
    private SupplierServiceMessageEntity entity = null;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_service_message;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setTextTitleName("服务");
        setBackOnclickListner(mContext);
        orderMessageUtil = new OrderMessageUtil(mContext);
        line_supplier = $(R.id.line_project_message_supplier);
        line_text = $(R.id.line_project_message_text);
        line_img = $(R.id.line_matter_message_img);
        httpModel = new HttpModel();
        line_signature = $(R.id.line_supplier_service_message_signature_fgx);
        tv_signature = $(R.id.tv_supplier_service_message_signature);
        tv_signature_botton = $(R.id.tv_supplier_service_message_signature_botton);
        rela_layout = $(R.id.rele_supplier_service_message_layout);
        signatureTopView = $(R.id.signa_supplier_service_message);
        list_signature = $(R.id.list_supplier_service_message_signature);
        scrollView = $(R.id.scro_supplier_service_message);
        list_signature.setDividerHeight(0);
        adapter_signature = new ItemOrderMessageSignatureAdapter(mContext);
        list_signature.setAdapter(adapter_signature);
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        scrollView.setOnScrollChangeListener(onScrollChangeListener);
        tv_signature_botton.setOnClickListener(onClickListener);
        signatureTopView.setAgreeOnclockListener(onClickListener);
        signatureTopView.setUnAgreeOnclockListener(onClickListener);
    }

    /**
     * scrollview的滑动状态变化监听事件
     */
    private View.OnScrollChangeListener onScrollChangeListener = new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            scrollviewYHeight = scrollY;
            setOnScrollStatus();
        }
    };


    /**
     * 根据滑动的距离修改浮动按钮的状态
     */
    private void setOnScrollStatus() {
        int scrollVisibilityHright = rela_layout.getHeight() + scrollviewYHeight;//获取屏幕底部距离scrollview顶部的距离
        if (scrollVisibilityHright >= tv_signature.getTop() + tv_signature.getHeight()) {//浮动部分已经显示出来了
            tv_signature_botton.setVisibility(View.GONE);
        } else {
            tv_signature_botton.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 控件的点击事件
     */
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_supplier_service_message_signature_botton://底部浮动按钮——签字意见
                    int heightY = tv_signature.getTop() - scrollviewYHeight;
                    scrollView.scrollTo(0, heightY);
                    tv_signature_botton.setVisibility(View.GONE);
                    break;
                case R.id.tv_view_message_signature_agree://批准按钮
                    setOrderApproval("");
                    break;
                case R.id.tv_view_message_signature_unagree://退回按钮
                case R.id.line_view_message_signature_edt://底部输入框的点击事件
                    show_approve_remark_dialog();
                    break;
            }
        }
    };

    @Override
    protected void initdatas() {
        super.initdatas();
        Map<String, Object> map = new HashMap<>();
        map.put("id", getIntent().getIntExtra("id", 0));
        httpModel.getSupplierServiceMesage(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);

                if (model instanceof SupplierServiceMessageEntity) {
                    entity = (SupplierServiceMessageEntity) model;
                }
                if (entity != null && entity.getCode() == ConstantNetworkCode.SuccedCode && entity.getData() != null) {
                    List<MapListEntity> mapListEntities = new ArrayList<>();
                    mapListEntities.add(new MapListEntity("服务名称", entity.getData().getName()));
                    mapListEntities.add(new MapListEntity("服务编号", entity.getData().getSn()));
                    mapListEntities.add(new MapListEntity("执行标准/规范", entity.getData().getSpecification()));
                    orderMessageUtil.init_text_map_view(mapListEntities, line_text);
                    if (entity.getData().getSupplierList() != null) {
                        orderMessageUtil.init_suppliers_view(entity.getData().getSupplierList(), line_supplier);
                    }
                    onDataSucceed();
                    init_signature_view();
                    upDataShowSigantureView();
                } else {
                    onDataError(null);
                }
            }

            @Override
            public void onFailure(String msg) {
                onDataError(null);
            }
        });


    }

    /**
     * 初始化签字意见
     */
    private void init_signature_view() {
        if (entity.getData().getConfirmLogs() != null && entity.getData().getConfirmLogs().size() > 0 && getIntent().getBooleanExtra("show_siganture", true)) {
            //签字意见并获取签字意见列表未录入意见的数据最大的id
            List<OrderSignatureEntity> confirmLogs = new ArrayList<OrderSignatureEntity>();
            for (int i = 0; i < entity.getData().getConfirmLogs().size(); i++) {
                OrderSignatureEntity sigantureEntity = entity.getData().getConfirmLogs().get(i);
                if (sigantureEntity.getAppliedTimeLabel() != null && sigantureEntity.getAppliedTimeLabel().length() > 0) {
                    confirmLogs.add(sigantureEntity);
                } else {
                    if (sigantureEntity.getId() < sigantureId || sigantureId == 0) {
                        sigantureId = sigantureEntity.getId();
                    }
                }
            }
            //更新签字意见列表
            adapter_signature.setdate(confirmLogs);
        } else {
            list_signature.setVisibility(View.GONE);
            line_signature.setVisibility(View.GONE);
            tv_signature.setVisibility(View.GONE);
            tv_signature_botton.setVisibility(View.GONE);
        }
    }

    public void upDataShowSigantureView() {
        //审核状态为待审核，单据状态流转中，显示签字意见输入框
        if (entity.getData().getTransformStatusLabel().equals(OrderStatusUtil.FLOW_FLOW) && entity.getData().getConfirmStatusLabel().equals(OrderStatusUtil.STATUS_UNAPPROVE)) {
            signatureTopView.setVisibility(View.VISIBLE);
        } else {
            signatureTopView.setVisibility(View.GONE);
        }
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setOnScrollStatus();
            }
        }, 200);
    }

    /**
     * 显示批准输入框的弹框
     */
    private void show_approve_remark_dialog() {
        final DialogApproveUtil dialogApproveUtil = new DialogApproveUtil(mContext);
        dialogApproveUtil.show_approve_dialog(signatureTopView, 30);
        dialogApproveUtil.setApproveOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogApproveUtil.dismissPopupWindow();
                setOrderApproval(dialogApproveUtil.getEdtMessage());
            }
        });
        dialogApproveUtil.setUnApproveOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialogApproveUtil.getEdtMessage().length() == 0) {
                    ToastUtils.show_toast("请填写签字意见");
                } else {
                    dialogApproveUtil.dismissPopupWindow();
                    setOrderReject(dialogApproveUtil.getEdtMessage());
                }

            }
        });

    }

    /**
     * @param opinion 对单据执行批准的操作
     */
    private void setOrderApproval(@NonNull String opinion) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", sigantureId);
        map.put("opinion", opinion);
        Dialog_util.start_NetworkRequests_diolog(mContext);
        httpModel.setOrderApproval(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                Dialog_util.close_NetworkRequests_diolog();
                ToastUtils.show_toast(model.getMessage());
                if (model.getCode() == ConstantNetworkCode.SuccedCode) {
                    setResult(RESULT_OK);
                    line_text.removeAllViews();
                    line_supplier.removeAllViews();
                    initdatas();
                }
            }

            @Override
            public void onFailure(String msg) {
                Dialog_util.close_NetworkRequests_diolog();
            }
        });
    }

    /**
     * @param opinion 对单据执行退回的操作
     */
    private void setOrderReject(@NonNull String opinion) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", sigantureId);
        map.put("opinion", opinion);
        Dialog_util.start_NetworkRequests_diolog(mContext);
        httpModel.setOrderReject(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                Dialog_util.close_NetworkRequests_diolog();
                ToastUtils.show_toast(model.getMessage());
                if (model.getCode() == ConstantNetworkCode.SuccedCode) {
                    setResult(RESULT_OK);
                    line_text.removeAllViews();
                    line_supplier.removeAllViews();
                    initdatas();
                }
            }

            @Override
            public void onFailure(String msg) {
                Dialog_util.close_NetworkRequests_diolog();
            }
        });
    }
}
